<?php
class AppController extends Controller
{
	function beforeFilter() {
		$user = array();

		/*
		 * The code below is used to get userid and user role from user logged in.
		 * Parts of this code is provided by GreyPath
		 */
		// Create session name with the prefix is SESS
		$Drupal_session_name = "SESS" . md5("greypath.com");
		// If session name is found in cookie
		if(isset($_COOKIE[$Drupal_session_name])) {
			// Get the value of cookie for session name
			$cvalue = $_COOKIE[$Drupal_session_name];
			// Connect to database server to look up for database
			// For testing in local environment we are using localhost database settings
			// When configure this to production server, need to change database data to production
			$Drupal_db = mysql_connect("localhost","root","password");
			$db_prefix = '';
			mysql_select_db ( "greyway_drupal" , $Drupal_db );
			$q = mysql_query("SELECT uid FROM {$db_prefix}sessions WHERE sid='$cvalue'");
			$row = mysql_fetch_array($q);
			// If user is found
			if($row['uid'] != "" and $row['uid'] != 0) {
				// Get user ID
				$suid = $row['uid'];
				$user['id'] = $suid;
				// Get username and mail from users data. This data can be used in the future
				$q = mysql_query("SELECT name, mail FROM {$db_prefix}users WHERE uid='$suid'");
				$Drupalvett = mysql_fetch_array($q);
				$username = $Drupalvett['name'];
				$email = $Drupalvett['mail'];
				$user['username'] = $username;
				$user['email'] = $email;
				// Get user roles
				$sRolesQuery = "SELECT name FROM {$db_prefix}role WHERE rid in (select rid from users_roles as ur WHERE ur.uid ='$suid')";
				$roles = mysql_query($sRolesQuery);
				
				$userRoles = array();
				while ($eachRow = mysql_fetch_row($roles)) {
					$userRoles[] = $eachRow[0];
				}

				// Set user roles
				$user['userRoles'] = $userRoles;

				// Check if user has Lyceum Administrator role
				foreach ($userRoles as $userRole) {
					if($userRole == 'Lyceum Administrator') {
						$user['isLyceumAdmin'] = true;
						break;
					}
				}
			}
		}

		// If user is not found or user is not a Lyceum Administrator, re-direct user to greypath home page to login
		if ($user['id'] == "" or !$user['isLyceumAdmin']) {
			$this->redirect('http://localhost/greypath/', null, true);
			// For deploy in production
			// $this->redirect('http://www.greypath.com/', null, true);
			exit();
		}
		
		$this->set('user', $user);
		return $user;
	}
}
?>